/**
 * create by young (young2f@outlook.com) on 2020/9/16
 */


'use strict';
import React from 'react';
import {AutoComplete, Button, Form, Input, InputNumber, notification, Select, Table} from 'antd';

import FormBase from '../../../components/Base/FormBase';
import {connect} from "dva";
import moment from 'moment';
import 'moment/locale/zh-cn';
import DescGroup from "../../../components/DescriptionGroup";
import ViewTitle from "../../../components/ViewTitle";
import {FormField, FormLayout, ModalFooter} from "antd-extra";
import notify from "../../../components/NotificationExtra";
import styles from "../../index.less";

const {Option} = Select;
moment.locale('zh-cn');
const table = 'ProcureOrder';
@Form.create()
@connect(({
            user,
            global,
            dynamicLabel,
            material,
            store, procure
          }) => ({...user, ...material, ...dynamicLabel, ...global, ...procure, ...store}))
export default class ModalCreateAndSelectMaterial extends FormBase {
  constructor(props) {
    super(props);
    const {form, cols = 1, materials = [], record = {}} = this.props;
    this.state = {materials};
  }

  componentDidMount() {
    this.onDataLoad().then(res => this.setState(res));
  }

  async onDataLoad() {
    console.log('this.state.materialCode', this.state.materialCode);
    const {materialCode} = this.state;
    if (materialCode) {
      const res = await this.props.dispatch({
        type: 'store/findOne',
        payload: {table, code: materialCode}
      });
      console.log('findUseMaterials', res);
      const {result = {}} = res;
      const {storeCount = 0} = result;
      return {storeCount};
    }
    return {storeCount: 0};
  }


  renderFoot = () => {
    const {foot, value, modalRef, form, callback} = this.props;

    if (foot) {
      return foot(value, modalRef);
    } else {
      return (
        <ModalFooter>
          <Button type="primary" onClick={() => {
            const {modalRef, record = {}} = this.props;
            form.validateFields((err, values) => {
              if (err) {
                const {code} = err;
                const {errors} = code;
                errors.forEach(item => {
                  notification.error(item);
                });
                return;
              }
              //
              // _.merge(values, this.state);
              // _.merge(record, values);

              // const {useMaterials, lotId, materialCount} = record;
              // _.map(useMaterials, item => {
              //   const {_code, useCount, count} = item;
              //   if (lotId === _code) {
              //     const temp = materialCount + useCount;
              //     record.useCount = temp;
              //     console.log('useCount:', temp, "count", count);
              //     if (temp > count) {
              //       notify({
              //         type: "warning",
              //         message: `原料数量 ${materialCount} 超过采购可用数量${count - useCount}！`
              //       });
              //     }
              //   }
              // });

              callback(values);
              modalRef.close();
            });
          }}>确定</Button>

          <Button onClick={() => {
            modalRef.close();
          }}>取消</Button>
        </ModalFooter>
      );
    }
  };

  onUseMaterialSelect = (value, option) => {
    const {key, props} = option;
    const {label} = props;

    this.state['lotId'] = key;
    this.state['procureOrderCode'] = label;
    // this.state[`${label}`] = value;
    //
    const material = _.find(this.state.useMaterials, item => {
      return item._code === key;
    });

    const {useCount, count} = material;
    notify({type: "success", message: `该物料采购数量：${count},已占用数量：${useCount}`});
    // this.state["subcategory"] = material ? material.subcategory : '';
    // this.state["materialCode"] = material && material.code ? material.code : 'MAT' + new Date().valueOf();

  };
  getUseMaterialOpt = (list) => {
    return list.map(opt => (<Option key={opt._code}
                                    value={opt.name + " " + opt.subcategory + " " + opt.spec + " " + opt.target + " " + opt._code}
                                    label={opt.orderCode}>
        {opt.name + " " + opt.subcategory + " " + opt.spec + " " + opt.target + " " + opt._code}
      </Option>
    ));
  };
  getMaterialOpt = (list) => {
    return list.map(opt => (
      <Option key={opt.code}
              value={opt.name + " " + opt.subcategory + " " + opt.spec + " " + opt.type + " " + opt.number + " " + opt.code}
              label={'material'}>
        {/*{<Tooltip title={opt.code+opt.name+" "+opt.subcategory+" "+opt.spec}> {opt.name}</Tooltip>}*/}
        {opt.name + " " + opt.subcategory + " " + opt.spec + " " + opt.type + " " + opt.number + " " + opt.code}
      </Option>
    ));
  };
  onSearch = searchText => {
    const {materials = []} = this.props;
    console.log('searchText', searchText);
    if (!searchText || searchText === '') {
      this.state.materials = materials;
      const _temp = this.state;
      this.setState(_temp);
      return;
    }
    console.log('searchText materials', this.props.materials);
    const temp = [];
    _.map(this.props.materials, item => {
      const {name} = item;
      if (name.includes(searchText)) {
        temp.push(item);
      }
    });
    const _temp = this.state;
    _temp.materials = temp;
    this.setState(_temp);
  };

  getMaterialInfo() {
    const {form, cols = 2, record = {}} = this.props;
    const {useMaterials = [], materials = [], storeCount = 0} = this.state;

    // if (materialCode !== undefined && useMaterials.length === 0) {
    //   notify({type: "success", message: `该物料采购数量为0`});
    // }
    const {
      code='MAT'+Date.now().valueOf(),
      name,
      spec,
      subcategory,
      number,
      unit = "KG",
      type,
      materialCount = 0,
      useMaterial,
      materialContent = 0,
      cost = 0
    } = record;
    return <FormLayout form={form} cols={cols}>
      <FormField
        label={'物料编码'}
        name={'code'}
        initialValue={code}
      >
        <Input style={{width: '100%'}}
               disabled
        ></Input>
      </FormField>
      <FormField
        label={'物料名称'}
        name={'name'}
        initialValue={name}
      >
        <Input style={{width: '100%'}}

        ></Input>
      </FormField>
      <FormField
        label={'形态'}
        name={'subcategory'}
        initialValue={subcategory}
      >
        <Input style={{width: '100%'}}

        ></Input>
      </FormField>
      <FormField
        label={'物料规格'}
        name={'spec'}
        initialValue={spec}
      >
        <Input style={{width: '100%'}}

        ></Input>
      </FormField>
      <FormField
        label={'物料编号'}
        name={'number'}
        initialValue={number}
      >
        <Input style={{width: '100%'}}

        ></Input>
      </FormField>
      <FormField
        label={'物料类别'}
        name={'type'}
        initialValue={type}
      >
        <Input style={{width: '100%'}}

        ></Input>
      </FormField>
      <FormField
        label={'物料单位'}
        name={'unit'}
        initialValue={unit}
      >
        <Input style={{width: '100%'}}

        ></Input>
      </FormField>
      <FormField
        label={'当前库存'}
        name={'storeCount'}
        initialValue={storeCount}
      >
        <InputNumber
          disabled
        ></InputNumber>
      </FormField>
      {/*<FormField*/}
      {/*  label={'可用采购原料'}*/}
      {/*  name={'useMaterial'}*/}
      {/*  required={true}*/}
      {/*  initialValue={useMaterial}*/}
      {/*>*/}
      {/*  <AutoComplete style={{width: '100%'}}*/}
      {/*                dataSource={this.getUseMaterialOpt(useMaterials)}*/}
      {/*                allowClear*/}
      {/*                onSelect={this.onUseMaterialSelect}*/}

      {/*  >*/}
      {/*  </AutoComplete>*/}
      {/*</FormField>*/}
      <FormField
        label={'原料含量'}
        name={'materialContent'} initialValue={materialContent}
      >
        <Input style={{width: '100%'}}></Input>
      </FormField>
      <FormField
        label={'原料用量'}
        name={'materialCount'} initialValue={materialCount}
      >
        <InputNumber style={{width: '100%'}}></InputNumber>
      </FormField>

      <FormField
        label={'成本'}
        name={'cost'} initialValue={cost}
      >
        <Input style={{width: '100%'}}></Input>
      </FormField>
      {/*<FormField*/}
      {/*  label={'物料说明'}*/}
      {/*  name={'memo'} initialValue={cost}*/}
      {/*>*/}
      {/*  <a style={{width: '100%'}}>{}</a>*/}
      {/*</FormField>*/}
    </FormLayout>;
  }

  render() {
    const {style} = this.props;

    return (
      <div style={{...style}}>
        {this.getMaterialInfo()}
        {/*{<ViewTitle*/}
        {/*  title={'采购原料清单'}*/}
        {/*></ViewTitle>}*/}
        {/*{<Table*/}
        {/*  className={styles.antTable}*/}
        {/*  bordered={true}*/}
        {/*  columns={this.getDicTableCols(model, this.onCreateOrEdit, this.onDelete)}*/}
        {/*  dataSource={data}*/}
        {/*  scroll={{x: true}}*/}
        {/*  pagination={true}*/}
        {/*></Table>}*/}
        {this.renderFoot()}
      </div>

    );
  }
}

